<template>
  <a-card>
    <p style="text-align: center; font-size: 18px">采购入库退库</p>
    <br />
    <!-- 顶部信息 -->

    <a-form-model v-bind="layout" :model="form" :rules="rules" ref="ruleForm">
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="单据号" ref="document" prop="document">
            <a-input v-model="form.document" style="border: 0" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            ref="documentDate"
            label="单据日期"
            prop="documentDate"
          >
            <a-date-picker
              v-model="form.documentDate"
              @change="
                (a, b) => {
                  this.form.a = a;
                  this.form.documentDate = b;
                  this.form.balance = b;
                  this.DataSource.forEach((item, index) => {
                    this.DataSource[index].storageDate = b;
                  });
                }
              "
              type="date"
              style="width: 100%"
              format="YYYY-MM-DD"
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" ref="depotName" prop="depotName">
            <a-select
              v-model="form.depotName"
              @change="formDepotNameSelectChange"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="
                  item.depotId + '|' + item.depotNo + '|' + item.depotName
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="供应商" ref="supplier" prop="supplier">
            <a-select
              v-model="form.supplier_dictText"
              @change="getfarmerId"
              @search="getAllfarmerList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in supplierList"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="收发类别"
            ref="sendReceiveType"
            prop="sendReceiveType"
          >
            <a-select
              v-model="form.sendReceiveType"
              style="width: 100%"
              @change="shoufaleibieMethod"
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="库存组织"
            ref="kucunzuzhi"
            prop="kucunzuzhi"
          >
            <a-select v-model="form.kucunzuzhi" style="width: 100%">
              <a-select-option
                v-for="(item, index) in kucunzuzhiList"
                :key="index"
                :value="item.bodyname"
                >{{ item.bodycode }} {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="业务类型"
            ref="yewuleixing"
            prop="yewuleixing"
          >
            <a-select
              v-model="form.businame"
              style="width: 100%"
              showSearch
              @change="yewuleixingChange"
            >
              <a-select-option
                v-for="(item, index) in yewuleixingList"
                :key="index"
                :value="
                  item.busicode + '|' + item.businame + '|' + item.pkBusitype
                "
                >{{ item.businame }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="库管员"
            ref="cwhsmanager"
            prop="cwhsmanager"
          >
            <a-select
              v-model="form.cwhsmanager"
              placeholder="请输入查询"
              showSearch
              style="width: 100%"
              @search="searchUserInfoByUserName"
              @change="changekuguanyuan"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- <a-row>
          <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
            <a-form-model-item
              label="采购部门"
              ref="caigoubumen"
              prop="caigoubumen"
            >
              <a-input v-model="form.cdptid" disabled> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row> -->
      <a-row>
        <a-col :span="24" :style="{ textAlign: 'right' }">
          <a-modal
            title="物品入库信息表"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="addgoods_Ok"
            @cancel="addgoods_Cancel"
          >
            <!-- 添加物品入库的模态框存放XX信息 -->
          </a-modal>
        </a-col>

        <!-- 生成源单按钮组件 -->
        <PurchaseReturn
          v-if="!checkTag == true"
          :orderColumns="inputColumns"
          :listColumns="resultColumns"
          :ModalTitle="ModalTitle"
          :Modal="Modal"
          @origin-data="getOriginData"
          @origin-data2="getOriginData2"
          @balance="getbalance"
        >
        </PurchaseReturn>

        <!-- 第二排表格  单据对应表格 -->
        <a-table
          :columns="showgoods_columns"
          :data-source="DataSource"
          style="margin-top: 10px"
          :pagination="false"
          :scroll="{ x: 4000, y: 670 }"
          :row-key="rowkey"
        >
          <!-- 仓库编码  cangkubianma main table -->
          <span slot="depotNo" slot-scope="text, record">
            <a-select
              v-model="record.depotNo"
              showSearch
              style="width: 100%"
              @change="setGoodsList(record.key)"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotNo"
                :value="item.depotNo + '|' + item.depotName"
              >
                {{ item.depotNo }} {{ item.depotName }}
              </a-select-option>
            </a-select>
          </span>

          <!-- 仓位 -->
          <span slot="position" slot-scope="text, record">
            <a-tree-select
              v-model="record.position"
              style="width: 100%"
              :tree-data="record.positionList"
              @change="cangweiTreeSelectChang"
            >
            </a-tree-select>
          </span>

          <!-- 库位 -->
          <!-- <span slot="depotLocation" slot-scope="text, record">
              <a-tree-select
                v-model="record.depotLocation"
                style="width: 100%"
                :tree-data="record.positionList"
                @change="cangweiTreeSelectChang"
              >
              </a-tree-select>
            </span> -->

          <!-- 所属单位 -->
          <!-- <span slot="StorageUnit" slot-scope="text, record">
            <a-select
              v-model="record.StorageUnit"
              showSearch
              style="width: 100%"
              @change="storageUnitChange(record.key)"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotNo"
                :value="item.depotNo + '|' + item.depotName"
              >
                {{ item.depotNo }} {{ item.depotName }}
              </a-select-option>
            </a-select>
          </span> -->

          <!-- 存货编码 cunhuobianma main table-->
          <span slot="invcode" slot-scope="text, record">
            <a-select
              v-model="record.invcode"
              style="width: 100%"
              @search="handleSearch"
              @change="
                (val) => {
                  const arr = val.split('|');
                  record.inventoryId = arr[0];
                  record.invcode = arr[1];
                  record.inventoryId_dictText_dictText = arr[2];
                  record.invname = arr[2];
                  record.invcode_dictText = arr[1];
                  record.invspec_dictText = arr[3] || '';
                  record.invspec = arr[3] || '';
                  record.measname = arr[4];
                }
              "
              showSearch
            >
              <a-select-option
                v-for="item in goodsList"
                :key="item.inventoryId"
                :value="
                  item.inventoryId +
                  '|' +
                  item.invcode +
                  '|' +
                  item.invname +
                  '|' +
                  item.invspec +
                  '|' +
                  item.measname
                "
              >
                {{ item.invcode }} {{ item.invname }}
                {{ item.invspec }}
              </a-select-option>
            </a-select>
          </span>

          <!-- 单价 -->
          <span slot="unitPrice" slot-scope="text, record">
            <a-input-number
              v-model="record.unitPrice"
              style="width: 100%"
              :precision="6"
              :min="0"
              @change="changeprice(text, record)"
            />
          </span>
          <!-- 数量 -->
          <span slot="quantity" slot-scope="text, record">
            <a-input-number
              :precision="3"
              v-if="!checkTag"
              v-model="record.quantity"
              :min="minnumber"
              :max="maxnumber"
              @change="changenumber(text, record)"
            />
            <div v-if="checkTag">{{ record.quantity }}</div>
          </span>
          <!-- 金额 -->
          <span slot="money" slot-scope="text, record">
            <a-input-number
              :precision="2"
              v-model="record.money"
              @keydown="handleInput2"
              @change="changemoney(text, record)"
            >
            </a-input-number>
          </span>
          <!-- 扣重    是金额不是重量,金额从质检单里面自动获取
               @dblclick="showQualityModel"-->
          <span slot="deduction" slot-scope="text, record">
            <a-input v-model="record.deduction" />
          </span>
          <!-- 源单号 -->
          <span slot="sourceNumber" slot-scope="text">
            {{ text }}
          </span>

          <!-- 生产日期-->
          <span slot="productionDate" slot-scope="text, record">
            <a-date-picker
              v-model="record.productionDate"
              @change="
                (a, b) => {
                  record.a = a;
                  record.productionDate = b;
                }
              "
            />
          </span>
          <!-- 保质期(月) -->
          <span slot="shelfLife" slot-scope="text, record">
            <a-input v-model="record.shelfLife" />
          </span>
          <!-- 入库日期 -->
          <span slot="storageDate" slot-scope="text, record">
            <a-date-picker
              v-model="record.storageDate"
              @change="
                (a, b) => {
                  record.a = a;
                  record.storageDate = b;
                }
              "
            />
          </span>
          <!-- 是否赠品 -->
          <span slot="giveaway" slot-scope="text, record">
            <a-select
              v-model="record.giveaway"
              style="width: 100%"
              @change="changegiveaway(record.giveaway, record)"
            >
              <a-select-option
                v-for="item in giveAwayList"
                :key="item.title"
                :value="item.value"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </span>
          <!-- 备注 -->
          <span slot="remark" slot-scope="text, record">
            <a-input v-model="record.remark" />
          </span>
          <!-- <template slot="action" slot-scope="text, record"> -->
          <!-- <span>
              <a @click="cancle(record.key)">取消</a>
            </span> -->
          <!-- <span v-else>
              <a-popconfirm
                ok-text="确定"
                cancel-text="取消"
                @confirm="DeleteInfo(record.key)"
              >
                <template slot="title">
                  <p>确定删除？</p>
                </template>
                <a type="danger"> 删除 </a>
              </a-popconfirm>
            </span> -->
          <!-- </template> -->
        </a-table>
      </a-row>

      <!-- 添加一条信息 -->
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
      <div style="margin-top: 20px">
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="负责人"
              ref="responsiblePerson"
              prop="responsiblePerson"
            >
              <a-select
                v-model="form.responsiblePerson"
                style="width: 100%"
                showSearch
                @change="setResponsible_person"
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item ref="surveyor" label="检验人" prop="surveyor">
              <a-select
                v-model="form.surveyor"
                style="width: 100%"
                showSearch
                @change="
                  (value) => {
                    const arr = value.split('|');
                    this.form.surveyorId = arr[0];
                    this.form.surveyor = arr[2];
                  }
                "
              >
                <a-select-option
                  v-for="item in CheckerList"
                  :key="item.userId"
                  :value="item.userId + '|' + item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="检验人"
              ref="responsiblePerson"
              prop="responsiblePerson"
            >
              <a-select
                v-model="form.surveyor"
                style="width: 100%"
                showSearch
                @change="setSurveyor"
              >
                <a-select-option
                  v-for="item in CheckerList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="检验日期"
              ref="surveyDate"
              prop="surveyDate"
            >
              <a-date-picker
                v-model="form.surveyDate"
                type="date"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" ref="inspector" prop="inspector">
              <a-select
                v-model="form.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" ref="balance" prop="balance">
              <a-date-picker
                v-model="form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人" ref="formMaker" prop="formMaker">
              <a-input disabled v-model="form.formMaker"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </a-form-model>

    <!-- 提交按钮组  -->
    <div style="margin-top: 20px">
      <center>
        <!-- <a-button type="primary" style="margin-right: 20px" @click="printGo">
            打印
          </a-button> -->
        <a-button
          @click="handleSaveButton"
          :disabled="isAntiAudit"
          style="margin-right: 20px"
        >
          保存
        </a-button>
        <a-button
          @click="Auditfunction"
          style="margin-right: 20px"
          :disabled="!isAntiAudit"
        >
          审核
        </a-button>
        <!-- :disabled="ExamineDisplay" -->
        <!-- <a-button
            type="primary"
            style="margin-right: 20px"
            :disabled="!alreadyRecordTag"
          >
            提交
          </a-button> -->
        <!-- :disabled="ExamineDisplay" -->
      </center>
    </div>

    <!-- 质检单弹窗 -->
    <!-- <a-modal title="质检单" v-model="qualityVisible" @ok="handleOk" width="70%">
      <a-form v-bind="detailLayout" class="ant-advanced-search-form">
        <a-row>
          <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
            <a-form-item label="订单编号">
              <a-input v-model="form.orderNo" style="border: 0" disabled />
            </a-form-item>
          </a-col>

          <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
            <a-form-item label="订单日期">
              <a-input v-model="form.orderDate" style="border: 0" disabled />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-table :columns="qualityColumns" :data-source="qualityData">
        <a slot="name" slot-scope="text">{{ text }}</a>
      </a-table>
    </a-modal> -->

    <a-modal title="预览" v-model="printShow" width="70%" @ok="printOk">
      <div id="caigouPrint" style="width: 94%; margin: 0 auto">
        <div
          class="print-header"
          style="
            text-align: center;
            height: 40px;
            line-height: 40px;
            font-size: 20px;
          "
        >
          采购入库单
        </div>
        <div
          class="print-2header"
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
            font-size: 14px;
          "
        >
          <div style="margin-left: 10px">
            单据号：{{ printBaseInfo.document }}
          </div>
          <div style="margin-left: 10px">
            供应商：{{ printBaseInfo.supplier }}
          </div>
          <div style="margin-left: 10px">
            仓库：{{ printBaseInfo.depotName }}
          </div>
          <div style="margin-left: 10px">
            日期：{{ printBaseInfo.documentDate }}
          </div>
        </div>
        <div class="print-table">
          <table
            style="width: 100%; text-align: center; border-collapse: collapse"
            border="0"
            cellspacing="0"
            cellpadding="0"
          >
            <tr>
              <th>存货编码</th>
              <th>存货名称</th>
              <th>规格</th>
              <th>单位</th>
              <th>数量</th>
              <th>单价</th>
              <th>金额</th>
            </tr>
            <tr v-for="(tr, trInd) in printRenderData" :key="trInd">
              <td v-for="(td, tdInd) in tr" :key="tdInd">{{ td }}</td>
            </tr>

            <tr>
              <td>合计</td>
              <td></td>
              <td></td>
              <td></td>
              <td>{{ printBaseInfo.sumNum }}</td>
              <td></td>
              <td>{{ printBaseInfo.sumMoney }}</td>
            </tr>
          </table>
        </div>

        <div class="print-footer">
          <div style="margin-left: 10px">
            制单人：{{ printBaseInfo.singleProducer }}
          </div>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>
<script>
// ------- 公共接口 ------- ;
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();
// ------- 根据源单生产表单组件 ------- ;
import PurchaseReturn from "../../components/common/PurchaseReturn";
//采购入库页面
import { CaiGouRuKuHttp } from "@/services/modules/RuKuGuGuanLi/CaiGouRuKu";
const cgrkHttp = new CaiGouRuKuHttp(); // 采购入库

import moment from "moment";
import { mapState, mapGetters } from "vuex";
//通知提醒key值
// const key = "updatable";

// 这里是搜索后显示到的信息列

// ----- 主页面表格的列表来源    -----; raintodo
const showgoods_columns = [
  {
    title: "序号",
    align: "center",
    width: "80px",
    dataIndex: "key",
    key: "key",
  },
  // {
  //   title: "仓库编码",
  //   dataIndex: "depotNo",
  //   key: "depotNo",
  //   align: "center",
  //   width: "10%",

  //   scopedSlots: { customRender: "depotNo" },
  // },
  {
    title: "仓库名称",
    dataIndex: "depotName",
    key: "depotName",
    align: "center",
    width: "7%",
    scopedSlots: { customRender: "depotName" },
  },
  {
    title: "仓位",
    dataIndex: "position",
    key: "position",
    align: "center",
    width: "7%",
    scopedSlots: { customRender: "position" },
  },

  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
    width: "15%",
    scopedSlots: { customRender: "invcode" },
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
    width: "5%",
    // scopedSlots: { customRender: "invname" },
  },
  {
    title: "规格型号", // 没有 rain-fix  main table
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
    width: "5%",
    // scopedSlots: { customRender: "invspec" },
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
    width: "5%",
    // scopedSlots: { customRender: "measname" },
  },
  {
    title: "单价",
    dataIndex: "unitPrice",
    key: "unitPrice",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "金额",
    dataIndex: "money",
    key: "money",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "扣重",
    dataIndex: "deduction",
    key: "deduction",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "deduction" },
  },
  {
    title: "源单号",
    dataIndex: "sourceNumber",
    key: "sourceNumber",
    width: "7%",
    align: "center",
    scopedSlots: { customRender: "sourceNumber" },
  },
  {
    title: "生产日期",
    dataIndex: "productionDate",
    key: "productionDate",
    align: "center",
    width: "6%",
    scopedSlots: { customRender: "productionDate" },
  },
  {
    title: "保质期(月)",
    dataIndex: "shelfLife",
    key: "shelfLife",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "shelfLife" },
  },
  {
    title: "批次号",
    dataIndex: "batchNumber",
    key: "batchNumber",
    align: "center",
    width: "6%",
    scopedSlots: { customRender: "batchNumber" },
  },
  {
    title: "退库日期",
    dataIndex: "storageDate",
    key: "storageDate",
    align: "center",
    width: "6%",
    scopedSlots: { customRender: "storageDate" },
  },
  // {
  //   title: "是否赠品",
  //   dataIndex: "giveaway",
  //   key: "giveaway",
  //   align: "center",
  //   width: "5%",
  //   scopedSlots: { customRender: "giveaway" },
  // },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    width: "7%",
    scopedSlots: { customRender: "remark" },
  },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "left",
  //   width: "4%",
  //   scopedSlots: { customRender: "action" },
  // },
];
// ----- 采购订单生成采购入库单弹窗   上部分的表格 -----;
const inputColumns = [
  {
    title: "序号",
    dataIndex: "key",
    align: "center",
    scopeSlots: { customRender: "key" },
  },
  {
    title: "单据号",
    dataIndex: "document",
    align: "center",
    scopedSlots: { customRender: "document" },
  },
  {
    title: "单据日期",
    dataIndex: "documentDate",
    align: "center",
    scopedSlots: { customRender: "documentDate" },
  },
  {
    title: "业务类型",
    dataIndex: "yewuleixing",
    align: "center",
    scopedSlots: { customRender: "yewuleixing" },
  },

  {
    title: "供应商",
    dataIndex: "supplier_dictText",
    align: "center",
    scopedSlots: { customRender: "supplier_dictText" },
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];
// ----- 采购订单生成采购入库单弹窗   下部分的表格 -----;
const resultColumns = [
  {
    title: "序号",
    align: "center",
    dataIndex: "key",
    key: "key",
  },
  {
    title: "仓库名称",
    width: 80,
    align: "center",
    dataIndex: "depotId_dictText",
    // scopedSlots: { customRender: "depotId_dictText" },
  },
  {
    title: "存货编码",
    align: "center",
    dataIndex: "invcode",
    // scopedSlots: { customRender: "invcode" },
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
    scopedSlots: { customRender: "invname" },
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
    // scopedSlots: { customRender: "invspec" },
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
    scopedSlots: { customRender: "measname" },
  },
  // {
  //   title: "辅助单位", // 没有辅助单位 rain-fix:留着
  //   width: 100,
  //   dataIndex: " auxiliaryUnit",
  //   key: "auxiliaryUnit",
  //   align: "center",
  //   scopedSlots: { customRender: "auxiliaryUnit" },
  // },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    dataIndex: "unitPrice",
    key: "unitPrice",
    align: "center",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    dataIndex: "money",
    key: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "备注", // 没有备注 rain-fix:
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "单据状态",
    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];

export default {
  //组件
  components: {
    PurchaseReturn,
  },
  data() {
    return {
      printRenderData: [],
      printShow: false,
      printBaseInfo: {
        supplier: "",
        document: "",
        depotName: "",
        documentDate: "",
        singleProducer: "",
      },
      //计算属性
      getprice: "",
      getnumber: 1,
      getmoney: "",
      //数量输入框默认最小值是1
      minnumber: -Infinity,
      maxnumber: Infinity,

      isAntiAudit: false,

      form: {
        supplier_dictText: "",
        businame: "",
        busicode: "",
        id: "",
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        // StorageUnit: "", // 所属单位名称
        // StorageUnitId: "", // 所属单位Id
        // StorageUnitNo: "", // 所属单位编号
        department: "", // 部门名称
        deptId: "", // 部门id
        supplier: "", // 供应商
        sendReceiveType: "", // 收发类别名称
        kucunzuzhi: "",
        yewuleixing: "", //业务类型
        cwhsmanager: "", //库管员

        // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        formMaker: this.$store.state.user.info.username, // 制单人
        formMakerID: this.$store.state.user.info.id, // 制单人Id
      },

      //与用友互通传id保存
      saveidfor_U8c: "",

      rowkey: "",

      inputColumns,
      editingKey: "",
      selectedRowKeys: [],
      //页面布局

      layout: {
        labelCol: { span: 6, offset: 1 },
        wrapperCol: { span: 15, offset: 1 },
      },
      layoutButton: {
        labelCol: { span: 4, offset: 10 },
        wrapperCol: { span: 14, offset: 17 },
      },
      detailLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      ModalTitle: "采购退库申请单生成采购退库单",
      Modal: "源单",
      checkTag: false, // 审核标志
      updateTag: true, // 修改标志
      alreadyCheckTag: false, // 没审核
      alreadyRecordTag: false, // 记账标志
      qualityVisible: false, //质检单显示属性
      ExamineDisplay: true, // 审核、提交按钮是否显示

      resultColumns, // ----- 采购订单生成采购入库单 下部分的表格数据来源 -----;
      showgoods_columns, // 入库信息显示列名
      visible: false,
      confirmLoading: false,
      SearchVisible: false, //源单号详情请页面显示类型
      EntryVisible: false, //采购订单生成采购入库单
      qualityData: [], //质检单数据来源
      DataSource: [], //入库单数据来源
      rukudan_data: [], //入库单数据来源
      // ------- 字典表数据 ------- ;
      giveAwayList: [], // 是否赠品列表
      positionList: [], // 仓位列表
      shoufaleibieList: [], // 收发类别列表
      kucunzuzhiList: [], //库存组织列表
      yewuleixingList: [], //yewuleixing
      storageList: [], //仓库名称列表
      department: [], // 部门列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表
      // batchNumberList: [], // 批次号
      responsiblePersonList: [], // 负责人列表
      CheckerList: [], //检验人列表
      UserList: [], // 库管员列表

      //应该从采购系统接口获取数据
      supplierList: [], //供货商列表
      todayBatchNumber: null,

      // updateTag: true, // 修改标志
      goodsList: [],
      empty_: true,

      savebalance: Infinity,
      // 新增验证规则
      rules: {
        document: [
          { required: true, message: "单据号为必填项！", trigger: "blur" },
        ],

        documentDate: [
          { required: true, message: "单据日期为必填项！", trigger: "blur" },
        ],

        depotName: [
          { required: true, message: "仓库名称为必填项！", trigger: "blur" },
        ],
        //供应商后期加上了必填校验，因为同步用友的时候需要
        supplier_dictText: [
          { required: true, message: "供应商为必填项！", trigger: "blur" },
        ],

        sendReceiveType: [
          { required: true, message: "收发类别为必填项！", trigger: "blur" },
        ],
        kucunzuzhi: [
          { required: true, message: "库存组织为必填项！", trigger: "blur" },
        ],
        yewuleixing: [
          { required: true, message: "业务类型为必填项！", trigger: "blur" },
        ],
        cwhsmanager: [
          { required: true, message: "库管员为必填项！", trigger: "blur" },
        ],
        // responsiblePerson: [
        //   { required: true, message: "负责人为必填项！", trigger: "blur" },
        // ],
        // surveyor: [
        //   { required: true, message: "检验人为必填项！", trigger: "blur" },
        // ],
        // surveyDate: [
        //   { required: true, message: "检验日期为必填项！", trigger: "change" },
        // ],
        inspector: [
          { required: true, message: "审核人为必填项！", trigger: "blur" },
        ],
        // balance: [
        //   { required: true, message: "审核日期为必填项！", trigger: "blur" },
        // ],
        formMaker: [
          { required: true, message: "制单人为必填项！", trigger: "blur" },
        ],
      },
    };
  },

  watch: {
    $route: function (to, form) {
      if (to.path == "/purchaseCancel" && form.path == "/purchaseCancelList") {
        console.log("--------- 更新视图 采购入库  ----------");

        if (this.$route.query.document) {
          this.getMainListByDocment();
        }
      }
    },
  },

  computed: {
    //用于计算一些处理过的数据

    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),

    // ------- 多选函数 ------- ;
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
    // ------- 页面布局 ------- ;
    formItemLayout() {
      const { formLayout } = this;
      return formLayout === "horizontal"
        ? {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
          }
        : {};
    },
  },
  //生命周期函数
  mounted() {
    this.judgeDocument(); //判断单据号是否为空
    // this.getSaleDepartmentList(); // 获取销售部门
    // 获取客户
    // 获取收发类别
    // this.getPositionInformationList(); // 获取仓位列表
    // this.getAuxiliary_Unitlist(); // 获取辅助单位列

    // this.getAllfarmerList(); // 获取供应商信息
    // this.getSupplierList(); //供应商列表获取
    // this.getPosition(); // 获取仓位信息
    this.shoufaleibieListmethod(); //收发类别列表
    this.getAllCodeName(); //获取库存组织列表
    this.getsyncbusinesstype_U8c(); //获取业务类型
    this.getOriginalNumber(); // 生成源单号
    // this.setColumns(); // 生成多条数据
    this.getApplyOrder(); // 获取单据号
    this.getApplyStorage(); // 获取仓库
    this.getGiveawayList(); // 是否赠品列表
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.getCheckerList(); // 获取 质检人 检验人
    this.getTodayBatchNumber(); // rain-fix: 获取当天批次号
    // this.newMember(); //新增一条记录
    if (this.$route.query.document) {
      this.getMainListByDocment();
    }
  },

  methods: {
    judgeDocument() {
      setTimeout(() => {
        if (this.form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    // --- 打印初始化 ---
    printGo() {
      this.printShow = true;

      // 过滤物品编码
      let newData = this.DataSource.filter((item) => item.invcode != "");
      let form = this.form;

      let sumNum = 0;
      let sumMoney = 0;

      this.printRenderData = newData.map((item) => {
        sumNum += item.quantity;
        sumMoney += item.money;
        return [
          // 存货编码
          item.invcode,
          // 存货名称
          item.invname,
          // 规格
          item.invspec,
          // 单位
          item.measname,
          // 数量
          item.quantity,
          // 单价
          Number(item.unitPrice),
          // 金额
          item.money,
        ];
      });

      let depotName = form.depotName.split("|"); // 仓库名称

      this.printBaseInfo = {
        supplier: form.supplier_dictText, // 供应商
        document: form.document, // 单据号
        depotName: depotName[2], // 仓库名称
        documentDate: form.documentDate, // 单据日期
        singleProducer: form.formMaker, // 制单人
        sumNum: sumNum,
        sumMoney: sumMoney,
      };
    },

    // --- 打印函数 ---
    printOk() {
      let dommm = document.querySelector("#caigouPrint");

      let frameId = "caigouprintIframe";
      let iframe;

      try {
        // 生成iframe 与原始页面进行隔离
        iframe = document.createElement("iframe");
        document.body.appendChild(iframe);
        iframe.style.border = "0px";
        iframe.style.position = "absolute";
        iframe.style.width = "0px";
        iframe.style.height = "0px";
        iframe.style.right = "0px";
        iframe.style.top = "0px";
        iframe.setAttribute("id", frameId);
        iframe.setAttribute("src", new Date().getTime());
        iframe.doc = null;
        iframe.doc = iframe.contentDocument
          ? iframe.contentDocument
          : iframe.contentWindow
          ? iframe.contentWindow.document
          : iframe.document;
      } catch (e) {
        throw new Error(e + ". iframes may not be supported in this browser.");
      }
      if (iframe.doc == null) {
        throw new Error("Cannot find document.");
      }

      let getPrintWindow = {
        f: iframe,
        win: iframe.contentWindow || iframe,
        doc: iframe.doc,
      };

      getPrintWindow.doc.open();
      getPrintWindow.doc.write(
        `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>
            <style>
              .print-table table td,
              .print-table table th,
              .print-table table tr {
                border: 1px solid black;
              }
              .print-table table tr {
                height: 30px;
              }
            </style>
            <body>
                ${dommm.innerHTML}
            </body>
            </html>`
      );
      getPrintWindow.doc.close();

      let iframeWin = document.getElementById(frameId).contentWindow;
      console.log(iframeWin);
      iframeWin.focus();
      iframeWin.print();
    },

    changeprice(data, record) {
      console.log(record, "?2");
      record.getprice = record.unitPrice;
      //  record.money = this.$set(
      //   record,
      //   "money",
      //   this.unitPrice * this.quantity
      // );
    },
    changenumber(data, record) {
      //判断第一个数量的输入框是正数还是负数，然后进行限制
      if (record.key == 1 && record.quantity > 0) {
        // this.minnumber = 0;
        this.maxnumber = Infinity;
        //通知提醒框
        // this.$notification.open({
        //   key,
        //   message: "提示",
        //   description: "注意！当前判定为入库，数量填写必须是正数",
        //   icon: <a-icon type="caret-right" style="color: #108ee9" />,
        //   onClick: () => {
        //     console.log("Notification Clicked!");
        //   },
        // });
      }
      if (record.key == 1 && record.quantity < 0) {
        this.maxnumber = 0;
        // this.minnumber = -Infinity;
        //通知提醒框
        // this.$notification.open({
        //   key,
        //   message: "提示",
        //   description: "注意！当前判定为退库，数量填写必须是负数",
        //   icon: <a-icon type="caret-left" style="color: #eb2f96" />,

        //   onClick: () => {
        //     console.log("Notification Clicked!");
        //   },
        // });
      }
      //计算单价
      console.log(record, "?2");
      console.log("data", data);
      // if (Number(record.quantity) > Number(this.savebalance)) {
      //   this.$message.error("超过源单物品数量!");
      //   record.quantity = this.$set(
      //     record,
      //     "quantity",
      //     this.savebalance
      //   );
      // }
      record.getmoney = record.money;
      record.getnumber = record.quantity;
      if (record.getmoney !== undefined) {
        record.unitPrice = this.$set(
          record,
          "unitPrice",
          record.getmoney / record.getnumber
        );
      }
    },
    changemoney(data, record) {
      console.log(record, "?2");
      record.getnumber = record.quantity;
      record.getmoney = record.money;
      if (record.quantity !== undefined) {
        record.unitPrice = this.$set(
          record,
          "unitPrice",
          record.getmoney / record.getnumber
        );
      }
    },

    handleInput2(e) {
      // 通过正则过滤小数点后两位
      e.target.value = e.target.value.match(/^\d*(.?\d{0,1})/g)[0] || null;
    },
    /**
     * @description: 获取主列表
     * @param {*}
     * @return {*}
     * http://localhost:8081/#/rukuguanli/CaiGouRuKu?document=CGRK-202012260116&auditMark=2&singleProducer=92052d0af1924655c64a751d396e5d18
     */
    handleSearch(value) {
      //模糊查询
      this.goodsList = [];
      console.log("value", value);
      let query = "?name=" + value;
      console.log("query", query);
      if (value == "" || value == null) {
        this.goodsList = [];
      } else {
        comHttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].invspec == "null" ||
              res.result[i].invspec == null
            ) {
              res.result[i].invspec = "";
            }
            if (
              res.result[i].measname == "null" ||
              res.result[i].measname == null
            ) {
              res.result[i].measname = "";
            }
            let data = {
              inventoryId: res.result[i].pkInvbasdoc, //存货 id
              invcode: res.result[i].invcode, //存货编码
              invname: res.result[i].invname, //存货名称
              invspec: res.result[i].invspec, //规格型号
              measname: res.result[i].measname, //单位
            };
            this.goodsList.push(data);
          }
        });
      }
    },
    getMainListByDocment() {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      this.editOrAdd = "edit";
      let _query = "";
      const document = this.$route.query.document;
      const auditMark = this.$route.query.auditMark;
      const singleProducer = this.$route.query.singleProducer;
      _query += "?pageSize=500&inOutIdentification=3"; // 内容数量 入库
      _query += `&auditMark=${auditMark}`; // 未审核:2 审核：1
      _query += `&document=${document}`; // 单据号
      _query += `&singleProducer=${singleProducer}`; // 制单人
      comHttp.getInOrOutStorageOrderAndGoodsList(_query).then((res) => {
        console.log(res, "信息");
        let _data = res.result.records;
        let firstData = _data[0];
        this.form.document = firstData.document; // 单据号
        this.form.documentDate = firstData.documentDate; // 单据日期
        // this.form.depotName = firstData.depotId_dictText; // 仓库名称
        // this.form.StorageUnit = firstData.storageUnit_dictText; // 所属单位
        this.form.kucunzuzhi = firstData.pkCalbody; // 库存组织
        this.form.yewuleixing = firstData.cbiztype; // 业务类型id
        this.form.businame = firstData.cbiztype_dictText; // 业务类型name

        this.form.id = firstData.id;
        this.form.depotName = firstData.storname; // 仓库名称
        // this.form.StorageUnit = firstData.storageUnit_dictText; //所属单位

        this.form.supplier = firstData.supplier; // 供应商
        this.form.supplier_dictText = firstData.supplier_dictText; // 供应商
        // 收发类型
        this.form.sendReceiveType = firstData.sendReceiveType_dictText;
        this.form.sendReceiveTypeId = firstData.sendReceiveType;
        // 负责人
        this.form.responsiblePersonId = firstData.responsiblePerson;
        this.form.responsiblePerson = firstData.responsiblePerson_dictText;
        // responsiblePerson  检验人
        this.form.surveyorId = firstData.inspector;
        this.form.inspector = firstData.inspector;
        this.form.surveyor = firstData.inspector_dictText;
        // 检验日期    //!!!!!!!!!!!!!!
        this.form.surveyDate = moment().format("YYYY-MM-DD");

        //库管员
        this.form.cwhsmanager =
          firstData.cwhsmanagerid1_dictText + firstData.cwhsmanagerid_dictText;
        this.form.cwhsmanagerid = firstData.cwhsmanagerid;

        // 审核人
        this.form.inspectorId = firstData.inspector;
        this.form.inspector = firstData.inspector_dictText;

        let options = _data.map((item, index) => {
          return {
            key: index + 1,
            // auxiliaryUnit: 0, // 辅助单位 现在暂时没有
            batchNumber: item.batchNumber, // 批次号
            deduction: item.deduction, // 扣重
            depotId: item.pkStordoc, // 仓库编码（库存组织外键）
            depotNo: item.storcode, // 仓库编码（库存组织外键）
            depotName: item.storname, // 仓库编码（库存组织外键）
            depotLocation: item.depotLocation, // 库位
            giveaway: item.giveaway, // 是否赠品(2否，1是)
            money: item.money, // 金额
            // position: item.position, // 仓位
            productionDate: item.productionDate, // 生产日期
            quantity: item.quantity, // 数量
            remark: item.remark, // 备注
            shelfLife: item.shelfLife,
            sourceNumber: item.sourceNumber, // 源单单号（外键）
            storageDate: item.storageDate, // 入库日期
            // StorageUnitId: item.storageUnit, // 所属单位（库存组织外键）
            // StorageUnit: item.storageUnit_dictText, // 所属单位（库存组织外键）
            invcode: item.invcode, // 存货编码
            invname: item.invname, // 存货编码
            inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
            invspec: item.invspec, // 规格型号
            measname: item.measname, // 单位
            unitPrice: item.unitPrice, // 单价
            twoId: item.twoId, // 数组内传递的id
          };
        });
        this.DataSource = options;
      });
    },

    // 获取 质检人 检验人
    getCheckerList() {
      const roleName = "仓库检验人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        console.log("仓库检验人员:::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.CheckerList.push(data);
        }
      });
    },
    // ------- 生命周期函数 ------- ;
    // 默认设置五行，让用户方便添加
    setColumns() {
      let size = 1;
      this.DataSource = [];

      for (let i = 1; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotName: "", // 仓库名称
          depotNo: "", // 仓库编码
          invcode: "", // 存货编码
          invname: "", //  存货名称
          standardModel: "", //规格型号
          // invspec:"",//规格型号
          measname: "", // 单位
          department: "", // 部门名称
          supplier: "", //供货商
          // storageUnitId: "", // 所属单位Id
          // storageUnitNo: "", // 所属单位编号
          deptId: "", // 部门id

          checker: "", //检验人
          quantity: "", // 	数量
          surveyorId: "", //检验人ID
          position: "", // 仓位
          sourceNumber: "", // 源单单号（外键）
          giveaway: "", // 是否赠品
          remark: "", // 备注
          goodsList: [], // 物品信息列
          batchNumber: null, //批次号
          balance: "", // 审核日期
          inspectorId: "", // 审核人Id
          inspector: "", // 审核人名称
          responsiblePerson: "", // 负责人名称
          responsiblePersonId: "", // 负责人Id
          sendReceiveType: "", // 收发类别名称
          sendReceiveTypeId: "", // 收发类别Id
          invspec: "", //规格型号
        };
        this.DataSource.push(data);
      }
      console.log("this.DataSource", this.DataSource);
    },
    //获取供应商列表
    /*   getAllfarmerList() {
      this.supplierList = [];
      comHttp.getAllfarmerList().then((res) => {
        // console.log("----- 供应商列表信息 -----", res);
        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            title: res.result.records[i].suppilerName,
            value: res.result.records[i].id,
          };
          this.supplierList.push(data);
        }
      });
    }, */
    // 获取供应商列表
    getfarmerId(value, options) {
      console.log("供应商::::", value, options.key);
      const newValue = value.split("|");
      console.log("newValue", newValue);
      this.form.supplier_dictText = newValue[1];
      this.form.supplier = newValue[2];
      // this.$set(this.form, "supplier_dictText", newValue[1]);
      // this.$set(this.form, "supplier", newValue[2]);
    },
    getAllfarmerList(value) {
      if (value != "") {
        comHttp
          .queryByLikeName("?customerName=" + value + "&custflag=1,3")
          .then((res) => {
            this.supplierList = [];
            console.log("所有的供应商信息::::", res);
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };

              this.supplierList.push(data);
            }
          });
        console.log("this.supplierList", this.supplierList);
      }
    },
    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          // 按钮状态改变:::::
          console.log(this.ExamineDisplay);
          this.ExamineDisplay = false;
        } else {
          this.ExamineDisplay = true;
        }
      });
    },
    // 生成源单号
    getOriginalNumber() {
      var date = new Date();
      // var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + month + strDate;
      return currentdate;
      // console.log("获取源单号");
    },
    //获取库存组织
    getAllCodeName() {
      cgrkHttp.getAllCodeName().then((res) => {
        console.log("库存组织", res);
        this.kucunzuzhiList = res.result;
      });
    },

    //获取业务类型
    getsyncbusinesstype_U8c() {
      cgrkHttp.getsyncbusinesstype_U8c().then((res) => {
        console.log("所有的业务类型", res);

        let _data = res.result;
        _data.forEach((item) => {
          // 匹配数字
          if (item.busicode.match(/^[0-9]{1,20}$/)) {
            if (item.busicode.substr(0, 1) == "1") {
              this.yewuleixingList.push(item);
            }
          }
        });
        console.log("筛选后的业务类型_1开头的用于采购", this.yewuleixingList);
      });
    },

    //收发类别列表
    shoufaleibieListmethod(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result;
      });
    },
    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      console.log("array[0]", array[0]);
      console.log("array[1]", array[1]);
      // 表格自动填充所属单位
      this.form.sendReceiveTypeId = array[0]; //收发类别id
      this.form.sendReceiveType = array[1]; //收发类别name
    },
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=CGRKT-";
      comHttp.getOrder(queryPath).then((res) => {
        this.form.document = res.message;
      });
    },
    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    /**
     * @description: 获取仓位列表
     * @param {*} id
     * @return {*}
     */
    getPositionList(id) {
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("----- 根据ID获取仓位列表res -----", res);
          console.log("----- id -----", id);
          positionList = res.result[0].children;
          resolve(positionList);
        });
      });
    },

    /**
     * @description: 部门字典表中每一项vlaue 变成 title 为了方便搜索
     * @param {*} dep
     * @return {*}
     */
    resetDepartmentTree(dep) {
      dep.forEach((item) => {
        // console.log("item", item);
        item.value = item.title;
        if (item.children) {
          this.resetDepartmentTree(item.children);
        }
      });
    },

    // 获取是否赠品列表
    getGiveawayList() {
      comHttp.getWarehouseGiveaway().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.giveAwayList.push(data);
        }
        console.log("this.giveAwayList", this.giveAwayList);
      });
    },
    yewuleixingChange(value) {
      const newValue = value.split("|");
      console.log(newValue);
      this.form.busicode = newValue[0];
      this.form.businame = newValue[1];
      this.form.yewuleixing = newValue[2];
    },
    //change 库管员
    changekuguanyuan(value) {
      console.log(value, "value");
      const newValue = value.split("|");
      this.form.cwhsmanager = newValue[0] + newValue[1];
      this.form.cwhsmanagerid = newValue[2];

      console.log("库管员id", this.form.cwhsmanager);
    },

    // ------- 主表单函数定义 ------- ;
    // 新增数据,新增表单数据和物品数据
    addNewData() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 过滤物品编码
          let newData = this.DataSource.filter((item) => item.invcode != "");
          let form = this.form;

          console.log(" --- newData ===", newData);
          console.log(" --- form ===", form);

          let _xxx = newData.map((item) => {
            return {
              objectInformationId: item.objectInformationId || "",
              // objectInformationId: 1579,

              // auxiliaryUnit: 0, // 辅助单位 现在暂时没有
              batchNumber: item.batchNumber, // 批次号
              // contractor: "", // 承包户（外键）
              // currency: "", // 币种
              // currencyAmount: 0, // 本币金额
              deduction: Number(item.deduction) || 0, // 扣重
              // deliveryDate: "", // 出库日期
              depotId: item.depotId, // 仓库编码（库存组织外键）
              depotLocation: item.depotLocation || null, // 库位
              // expectedNo: '', // 预期号
              // farmers: "", // 农户（外键）
              // finishedProductType: 0, // 产成品分类
              giveaway: Number(item.giveaway), // 是否赠品(2否，1是)
              inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
              money: item.money, // 金额
              // originalCurrency: 0, // 原币金额
              // otherId: 0, // 表一id
              position: item.position || null, // 仓位
              productionDate: item.productionDate, // 生产日期
              quantity: item.quantity, // 数量
              // receivingDepot: 0, // 收料仓库（外键）
              remark: item.remark || null, // 备注
              // shedNo: 0, // 棚号（外键）
              shelfLife: item.shelfLife, // 保质期
              sourceNumber: item.sourceNumber, // 源单单号（外键）
              storageDate: item.storageDate, // 入库日期
              // storageUnit: item.StorageUnitId, // 所属单位（库存组织外键）
              unitPrice: Number(item.unitPrice), // 单价
            };
          });

          let option = {
            saleOrderAddId: this.saveidfor_U8c || null,
            cwhsmanagerid: form.cwhsmanagerid, //库管员
            cbiztype: form.yewuleixing, //业务类型
            pkCalbody: form.kucunzuzhi, //库存组织
            auditMark: 2, // 审核标志, 1 已审核,2 未审核
            bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
            checker: form.surveyorId, // 检验人(传userid)
            // clientId: form.supplier, // 客户id
            // deliveryUnit: "", // 交货单位 不传交货单位
            // deptId: "", // 部门编码（外键）
            document: form.document, // 单据号
            documentDate: form.documentDate, // 单据日期
            balance: form.balance, // 审核日期
            // finishedProductDepot: 0, // 产成品仓库
            // id: 0,
            inOutCategoryIdentification: 7, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
            inOutIdentification: 3, // 入库、出库标识，1 入库，2 出库
            inspector: form.inspectorId, // 审核人(传userid)
            // projectsUnderConstruction: 0, // 在建项目
            responsiblePerson: form.responsiblePersonId, // 负责人 (传userid)）
            // salesman: "", // 业务员id
            sendReceiveType: (() => {
              let sendReceiveType = form.sendReceiveType;
              if (String(Number(sendReceiveType)) == "NaN") {
                sendReceiveType = form.sendReceiveTypeId;
              }
              return Number(sendReceiveType);
            })(), // 收发类型
            singleProducer: form.formMakerID, // 制单人(传userid)
            sort: form.documentDate, // 制单日期
            supplier: form.supplier, // 供应商 id
            // useTo: "", // 用途
            warehouseObjectInformationEntities: _xxx,
          };

          this.checkempty(_xxx); //校验
          if (this.empty_ === true) {
            comHttp.addInOrOutStorageOrderAndGoods(option).then((res) => {
              if (!res.success) {
                this.$message.error(res.message);
                return;
              }
              this.$message.success("提交成功");
              this.ResetForm(); //重置
            });
          }
        } else {
          console.log("false出现了");
        }
      });
    },

    // --- 获取当天批次号 ---
    getTodayBatchNumber() {
      cgrkHttp.getBatchNumber().then((res) => {
        // 自动生成批次号
        this.todayBatchNumber = res.message;
      });
    },

    // 获取源单数据 raintodo
    // rain-fix: xxxx
    getOriginData(data) {
      // console.log("获取源单数据出发后，显示目前数据的长度+1", lengthTemp);
      console.log("从根据源单生成传进来的数据", data);

      //用友互通用
      this.saveidfor_U8c = data[0].purchaseOrderId;
      console.log("this.saveidfor_U8c", this.saveidfor_U8c);
      this.form.depotName = data[0].depotId_dictText; //仓库名称
      this.form.depotId = data[0].depotId; //仓库名称id
      // let lengthTemp = this.DataSource.length + 1;
      // console.log(lengthTemp);
      // console.log(data);
      data.forEach((item, index) => {
        item.key = index + 1;
        item.batchNumber = this.todayBatchNumber; // 获取批次号
        item.depotName = data[0].depotId_dictText;
        item.depotId = data[0].depotId;
        //设置是否赠品的默认值
        item.giveaway = "2";
        //设置退库日期的默认值
        this.$set(item, "storageDate", moment().format("YYYY-MM-DD"));
      });
      this.DataSource = data;
    },
    getOriginData2(data) {
      // console.log("获取源单数据出发后，显示目前数据的长度+1", lengthTemp);
      console.log("从根据源单生成传进来的数据/供应商用", data);
      this.$set(this.form, "supplier", data[0].supplier);
      this.$set(this.form, "supplier_dictText", data[0].supplier_dictText);
      // this.form.supplier = data[0].supplierId;
      // this.form.supplier_dictText = data[0].supplier;

      // this.form.businame = data[0].cbiztype_dictText; //业务类型
      // this.form.cbiztype = data[0].cbiztype; //业务类型id

      // this.form.depotName = data[0].depotId_dictText; //仓库名称
      // this.form.depotId = data[0].depotId; //仓库名称id

      this.form.pkCalbody = data[0].pkCalbody; //库存组织
      this.form.kucunzuzhi = data[0].pkCalbody_dictText; //库存组织id
    },
    //获取现存
    getbalance(data) {
      console.log("现存111111", data);
      this.savebalance = data;
    },

    /**
     * @description: 修改数据函数
     * @param {*}
     * @return {*}
     */
    updateData() {
      // 过滤物品编码
      let newData = this.DataSource.filter((item) => item.invcode != "");
      let form = this.form;

      console.log(" --- newData ===", newData);
      console.log(" --- form ===", form);

      let _xxx = newData.map((item) => {
        return {
          id: item.twoId, // id
          // auxiliaryUnit: 0, // 辅助单位 现在暂时没有
          batchNumber: item.batchNumber, // 批次号
          // contractor: "", // 承包户（外键）
          // currency: "", // 币种
          // currencyAmount: 0, // 本币金额
          deduction: Number(item.deduction), // 扣重
          // deliveryDate: "", // 出库日期
          depotId: item.depotId, // 仓库编码（库存组织外键）
          depotLocation: item.depotLocation, // 库位
          // expectedNo: '', // 预期号
          // farmers: "", // 农户（外键）
          // finishedProductType: 0, // 产成品分类
          giveaway: item.giveaway, // 是否赠品(2否，1是)
          inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
          money: item.money, // 金额
          // originalCurrency: 0, // 原币金额
          // otherId: 0, // 表一id
          position: item.position, // 仓位
          productionDate: item.productionDate, // 生产日期
          quantity: item.quantity, // 数量
          // receivingDepot: 0, // 收料仓库（外键）
          remark: item.remark, // 备注
          // shedNo: 0, // 棚号（外键）
          shelfLife: item.shelfLife, // 保质期
          sourceNumber: item.sourceNumber || null, // 源单单号（外键）
          storageDate: item.storageDate, // 入库日期
          // storageUnit: item.StorageUnitId, // 所属单位（库存组织外键）
          unitPrice: Number(item.unitPrice), // 单价
        };
      });

      let option = {
        id: form.id,
        saleOrderAddId: this.saveidfor_U8c,
        cwhsmanagerid: form.cwhsmanagerid, //库管员
        cbiztype: form.yewuleixing, //业务类型
        pkCalbody: form.kucunzuzhi, //库存组织
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
        checker: form.surveyorId, // 检验人(传userid)
        // clientId: form.supplier, // 客户id
        // deliveryUnit: "", // 交货单位 不传交货单位
        // deptId: "", // 部门编码（外键）
        document: form.document, // 单据号
        documentDate: moment(this.form.documentDate).format("YYYY-MM-DD"), // 单据日期
        balance: moment(this.form.documentDate).format("YYYY-MM-DD"), // 单据日期

        // finishedProductDepot: 0, // 产成品仓库
        // id: 0,
        inOutCategoryIdentification: 7, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 3, // 入库、出库标识，1 入库，2 出库
        inspector: form.inspectorId, // 审核人(传userid)
        // projectsUnderConstruction: 0, // 在建项目
        responsiblePerson: form.responsiblePersonId, // 负责人 (传userid)）
        // salesman: "", // 业务员id
        sendReceiveType: (() => {
          let sendReceiveType = form.sendReceiveType;
          if (String(Number(sendReceiveType)) == "NaN") {
            sendReceiveType = form.sendReceiveTypeId;
          }
          return Number(sendReceiveType);
        })(), // 收发类型
        singleProducer: form.formMakerID, // 制单人(传userid)
        sort: form.documentDate, // 制单日期
        supplier: form.supplier, // 供应商 id
        // useTo: "", // 用途
        warehouseObjectInformationEntities: _xxx,
      };

      console.log(option);
      this.checkempty(); //校验
      if (this.empty_ === true) {
        comHttp.updateInOrOutStorageOrderAndGoods(option).then((res) => {
          if (!res.message) {
            this.$message.error("更新失败 请重新检查数据");
            return;
          }
          this.$message.success("更新成功");
        });
      }
    },

    /**
     * @description: 保存或者是修改
     * @param {*}
     * @return {*}
     */
    handleSaveButton() {
      if (this.editOrAdd === "edit") {
        console.log(" --- 触发更新 ---");
        this.updateData();
        return;
      }
      console.log(" --- 触发新增 ---");
      this.addNewData();
    },
    //校验是否为空
    checkempty(option) {
      console.log("option", option);
      this.empty_ = true;
      var message = []; //提示信息

      this.DataSource.forEach((element) => {
        console.log("element", element);
        // if (element.depotNo == "" || element.depotNo == null) {
        //   this.empty_ = false;
        //   message.push("仓库编码不能为空!" + "\xa0\xa0\xa0");
        // }
        if (element.quantity == "" || element.quantity == null) {
          this.empty_ = false;
          message.push("数量不能为空!" + "\xa0\xa0\xa0");
        }
        if (element.unitPrice == "" || element.unitPrice == null) {
          this.empty_ = false;
          message.push("单价不能为空!" + "\xa0\xa0\xa0");
        }

        if (element.invcode == "" || element.invcode == null) {
          this.empty_ = false;
          message.push("存货编码不能为空!" + "\xa0\xa0\xa0");
        }
      });
      if (!this.empty_) {
        for (var i = 0; i < message.length; i++) {
          for (var j = i + 1; j < message.length; j++) {
            if (message[i] == message[j]) {
              //第一个等同于第二个，splice方法删除第二个
              message.splice(j, 1);
              j--;
            }
          }
        }
        this.$message.error(message);
      }
    },

    // 审核函数
    Examine() {
      // this.form.balance = moment().format("YYYY-MM-DD");
      this.$message.success("审核成功");
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.form.responsiblePerson = array[1];
      this.form.responsiblePersonId = options.key;
    },

    // 表格添加新的一条记录
    newMember() {
      console.log("增加一条记录");
      this.savebalance = Infinity;
      this.DataSource.push({
        key: this.DataSource.length + 1,
        isNew: true,
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编码、
        quantity: "", //数量
        unitPrice: "", //单价
        invcode: "", // 存货编码
        invname: "", //  存货名称
        // standardModel: "", //规格型号
        invspec: "", //规格型号
        measname: "", // 单位
        position: "", // 仓位
        sourceNumber: "", // 源单单号（外键）
        batchNumber: "", // 批次号
        giveaway: "2", // 是否赠品
        remark: "", // 备注
        goodsList: [], // 物品信息列
        storageDate: moment().format("YYYY-MM-DD"), //入库日期
      });
      console.log("this.DataSource", this.DataSource);
    },

    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.form.inspector = array[1];
      this.form.inspectorId = options.key;
    },

    // ------- 质检单弹窗 ------- ;
    showQualityModel() {
      this.qualityVisible = true;
    },
    handleOk() {
      this.visible = false;
    },

    setSurveyor() {
      console.log("----- 获取检验人 -----");
    },
    // 获取物品信息
    getGoodSInfo(id) {
      return new Promise((resolve) => {
        comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
          let result = res.result;
          result.map((item) => {
            item.inventoryId = item.id;
            item.standardModel = item.invspec;
          });
          resolve(result);
        });
      });
    },
    // 表单仓库点击按钮
    formDepotNameSelectChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);

      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotId = array[0];
        this.DataSource[i].depotNo = array[1];
        this.DataSource[i].depotName = array[2];
        this.DataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        this.getGoodSInfo2(this.DataSource[i], array[0]);
        this.getPositionListById(this.DataSource[i], array[0]); // 获取仓位信息
      }
      console.log("仓库获取:::::", this.DataSource);

      // let array = value.split("|");
      // console.log(array[0]);
      // let key = option.key;
      // // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(key);
      // // 根据仓库查询物品信息,并存储到相应的物品信息表中
      // for (let i = 0; i < this.DataSource.length; i++) {
      //   this.DataSource[i].depotNo = array[0];
      //   this.DataSource[i].depotName = array[1];
      //   this.DataSource[i].depotId = key;
      //   this.DataSource[i].goodsList = goodsList;
      //   // this.positionList(this.DataSource[i]); // 获取仓位信息
      // }
      // console.log("仓库获取:::::", this.DataSource);
    },

    /**
     * @description: 获取物品信息
     * @param {*} id
     * @return {*}
     */
    getGoodSInfo2(target, id) {
      comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
        let result = res.result;
        result.map((item) => {
          item.inventoryId = item.id;
          item.standardModel = item.invspec;
        });
        target.goodsList = result;
        console.log("[INFO] [获取存货信息] \n", result);
      });
    },

    /**
     * @description: 获取仓位列表
     * @param {*} id
     * @return {*}
     */
    getPositionListById(target, depotId) {
      console.log("target", target);

      //清空仓位
      let array = [];
      this.$set(target, "positionList", array);

      comHttp
        .getPositionInformationListByDepotId("?id=" + depotId)
        .then((res) => {
          console.log("---------------- 【获取仓位列表】 -------------");
          console.log(res);

          if (res.result[0].children) {
            //解决仓位信息缓存
            let resetRes = res.result[0].children;
            const disableParent = (Tree) => {
              Tree.forEach((item) => {
                console.log(item, "111");
                if (item.children.length != 0) {
                  item[`disabled`] = true;
                } else {
                  disableParent(item.children);
                }
              });
            };

            disableParent(resetRes);

            this.$set(target, "positionList", resetRes);
          } else {
            let nosome = [];
            this.$set(target, "positionList", nosome);
          }
        });
    },

    // 获取存货信息
    getInventoryInfo(val) {
      console.log(val);

      // const arr = val.split("|");
      // record.inventoryId = arr[0];
      // record.invcode = arr[1];
      // record.inventoryId_dictText_dictText = arr[2];
      // record.invcode_dictText = arr[1];
      // record.invspec_dictText = arr[3] || "";
      // record.measname = arr[4];
    },
    /**
     * @description: 设置存货列表
     * @param {*}
     * @return {*}
     */

    async setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];

      console.log("target:::", target);
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库id
      target.depotName = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      // this.getGoodSInfo2(target, SotrageInfo.depotId);

      this.getPositionListById(target, SotrageInfo.depotId); // 获取仓位信息
    },

    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    // 设置所属单位, 上面表单触发事件
    setdataSourceStorageUnit(value, option) {
      let array = value.split("|");
      this.form.storageUnit = array[1];
      console.log(array);
      let key = option.key;
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].StorageUnitNo = array[0];
        this.DataSource[i].StorageUnit = array[1];
        this.DataSource[i].StorageUnitId = key;
      }
    },
    // 获取所属单位,表格触发事件
    storageUnitChange(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.StorageUnit.split("|");
      target.StorageUnitNo = array[0]; // 仓库id
      target.StorageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.StorageUnitId = SotrageInfo.depotId;
    },

    // ------- 主页面表格删除一行 ------- ;
    cancle(key) {
      console.log(this.DataSource.length);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        //序号重新排序
        for (let i = 0; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 重置
    Reset() {
      this.form = {
        documentDate: "", // 日期
        send_receive_type: "", // 收发类别
        storageId: "", // 申请仓库名称
        storageName: "", // 仓库名称名称
        departmentNo: "", // 部门编号
        department: "", // 部门
      };
      this.DataSource = [];
    },

    // 添加物品入库按钮后显示的表单，点击确认
    addgoods_Ok(e) {
      // 把数据发送到后端去

      this.confirmLoading = true;
      console.log(e);

      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
      }, 2000);
    },
    // 添加物品入库按钮后显示的表单，点击取消
    addgoods_Cancel(e) {
      console.log(e);
      console.log("Clicked cancel button");
      this.visible = false;
    },

    cangweiTreeSelectChang(val, old) {
      console.log("-------- cangweiTreeSelectChang --------");
      console.log(val, old);
    },
    // 结束

    //保存重置表单
    ResetForm() {
      this.form = {
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        // StorageUnit: "", // 所属单位名称
        // StorageUnitId: "", // 所属单位Id
        // StorageUnitNo: "", // 所属单位编号
        department: "", // 部门名称
        deptId: "", // 部门id
        supplier: "", // 供应商
        sendReceiveType: "", // 收发类别名称
        // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        formMaker: this.$store.state.user.info.username, // 制单人
        formMakerID: this.$store.state.user.info.id, // 制单人Id
      };
      this.getApplyOrder(); // 获取单据号
      this.setColumns(); //生命周期函数
      this.newMember();
    },

    // 查询人员信息列表
    searchUserInfoByUserName(value) {
      this.UserList = [];
      this.workNoList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        cgrkHttp.searchUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },
    //是否赠品的change函数
    changegiveaway(data, record) {
      this.rowkey = Math.random();
      console.log("选择的赠品value", data);
      console.log("选择的赠品record", record);
      this.$set(record, "giveaway", data);
    },
    //! 审核功能
    Auditfunction() {
      // 过滤物品编码
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let form = this.form;

      console.log(" --- newData ===", newData);
      console.log(" --- form ===", form);

      let _xxx = newData.map((item) => {
        return {
          id: item.twoId, // id
          // auxiliaryUnit: 0, // 辅助单位 现在暂时没有
          batchNumber: item.batchNumber, // 批次号
          // contractor: "", // 承包户（外键）
          // currency: "", // 币种
          // currencyAmount: 0, // 本币金额
          deduction: Number(item.deduction), // 扣重
          // deliveryDate: "", // 出库日期
          depotId: item.depotId, // 仓库编码（库存组织外键）
          depotLocation: item.depotLocation, // 库位
          // expectedNo: '', // 预期号
          // farmers: "", // 农户（外键）
          // finishedProductType: 0, // 产成品分类
          giveaway: item.giveaway, // 是否赠品(2否，1是)
          inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
          // money: item.remainingAmount, // 金额
          // originalCurrency: 0, // 原币金额
          // otherId: 0, // 表一id
          position: item.position, // 仓位
          productionDate: item.productionDate, // 生产日期
          quantity: item.quantity, // 数量
          // receivingDepot: 0, // 收料仓库（外键）
          remark: item.remark, // 备注
          // shedNo: 0, // 棚号（外键）
          shelfLife: item.shelfLife, // 保质期
          sourceNumber: item.sourceNumber || null, // 源单单号（外键）
          storageDate: item.storageDate, // 入库日期
          // unitPrice: Number(item.unitPrice), // 单价
        };
      });

      let option = {
        saleOrderAddId: this.saveidfor_U8c,
        cwhsmanagerid: form.cwhsmanager, //库管员
        cbiztype: form.businame, //业务类型
        pkCalbody: form.kucunzuzhi, //库存组织
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
        checker: form.surveyorId, // 检验人(传userid)
        // clientId: form.supplier, // 客户id
        // deliveryUnit: "", // 交货单位 不传交货单位
        // deptId: "", // 部门编码（外键）
        document: form.document, // 单据号
        documentDate: form.documentDate, // 单据日期
        // finishedProductDepot: 0, // 产成品仓库
        // id: 0,
        inOutCategoryIdentification: 1, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 1, // 入库、出库标识，1 入库，2 出库
        inspector: form.inspector, // 审核人(传userid)
        // projectsUnderConstruction: 0, // 在建项目
        responsiblePerson: form.responsiblePerson, // 负责人 (传userid)）
        // salesman: "", // 业务员id
        sendReceiveType: (() => {
          let sendReceiveType = form.sendReceiveType;
          if (String(Number(sendReceiveType)) == "NaN") {
            sendReceiveType = form.sendReceiveTypeId;
          }
          return Number(sendReceiveType);
        })(), // 收发类型
        singleProducer: form.formMakerID, // 制单人(传userid)
        sort: form.documentDate, // 制单日期
        supplier: form.supplier_dictText, // 供应商 id
        // useTo: "", // 用途
        warehouseObjectInformationEntities: _xxx,
      };

      console.log(option);
      this.checkempty(); //校验
      if (this.empty_ === true) {
        comHttp.updateInOrOutStorageOrderAndGoods(option).then((res) => {
          if (!res.message) {
            this.$message.error("审核失败 请重新检查数据");
            return;
          }
          this.$message.success("审核成功");
          //标志位修改
          this.postSynchronized("未同步");
          this.update_audit("未反审核");
          this.update_Mark(1);

          // 跳转回列表页面
          this.$router.push("/purchaseCancelList");
        });
      }
    },
    //! 是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
  },
};
</script>

<style>
.gutter-box {
  margin-bottom: 30px;
}

.editable-row-operations a {
  margin-right: 8px;
}

.print-table table td,
.print-table table th,
.print-table table tr {
  border: 1px solid black;
}
.print-table table tr {
  height: 30px;
}
</style>